<!-- src/views/company/PositionManagement.vue -->
<template>
  <div class="position-management">
    <div class="header">
      <h2>实习岗位管理</h2>
      <el-button type="primary" @click="showCreateDialog">发布新岗位</el-button>
    </div>

    <!-- 岗位列表 -->
    <el-table
      :data="positions"
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="title" label="岗位标题" min-width="150" />
      <el-table-column prop="department" label="部门" width="100" />
      <el-table-column prop="workLocation" label="工作地点" width="100" />
      <el-table-column prop="salaryRange" label="薪资范围" width="120" />
      <el-table-column prop="workType" label="工作类型" width="100">
        <template #default="scope">
          {{ getWorkTypeLabel(scope.row.workType) }}
        </template>
      </el-table-column>
      <el-table-column prop="recruitmentCount" label="招聘人数" width="100" />
      <el-table-column prop="deadline" label="截止日期" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.deadline) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getPositionStatusType(scope.row.status)">
            {{ getPositionStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewPositionDetail(scope.row)">查看</el-button>
          <el-button
            size="small"
            type="primary"
            @click="editPosition(scope.row)"
            :disabled="scope.row.status === 2"
          >
            编辑
          </el-button>
          <el-dropdown @command="handlePositionAction">
            <el-button size="small">
              更多<el-icon><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :command="{action: 'toggle', position: scope.row}"
                  :disabled="scope.row.status === 2"
                >
                  {{ scope.row.status === 0 ? '上线' : '下线' }}
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{action: 'delete', position: scope.row}"
                  :disabled="scope.row.status === 1"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: center;"
    />

    <!-- 岗位详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="岗位详情"
      width="700px"
    >
      <div v-if="selectedPosition" class="position-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="岗位标题">{{ selectedPosition.title }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ selectedPosition.department }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ selectedPosition.workLocation }}</el-descriptions-item>
          <el-descriptions-item label="薪资范围">{{ selectedPosition.salaryRange }}</el-descriptions-item>
          <el-descriptions-item label="工作类型">{{ getWorkTypeLabel(selectedPosition.workType) }}</el-descriptions-item>
          <el-descriptions-item label="招聘人数">{{ selectedPosition.recruitmentCount }}</el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ formatDate(selectedPosition.deadline) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getPositionStatusType(selectedPosition.status)">
              {{ getPositionStatusLabel(selectedPosition.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedPosition.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedPosition.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="岗位描述" :span="2">
            <div class="description-content">{{ selectedPosition.description }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="任职要求" :span="2">
            <div class="requirements-content">{{ selectedPosition.requirements }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 岗位创建/编辑对话框 -->
    <el-dialog
      v-model="positionDialogVisible"
      :title="isEditing ? '编辑岗位' : '发布新岗位'"
      width="700px"
    >
      <el-form
        :model="positionForm"
        :rules="positionRules"
        ref="positionFormRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="岗位标题" prop="title">
              <el-input v-model="positionForm.title" placeholder="请输入岗位标题" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
              <el-input v-model="positionForm.department" placeholder="请输入所属部门" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工作地点" prop="workLocation">
              <el-input v-model="positionForm.workLocation" placeholder="请输入工作地点" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="薪资范围" prop="salaryRange">
              <el-input v-model="positionForm.salaryRange" placeholder="例如：3000-5000" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工作类型" prop="workType">
              <el-select v-model="positionForm.workType" placeholder="请选择工作类型" style="width: 100%">
                <el-option label="全职" :value="1" />
                <el-option label="兼职" :value="2" />
                <el-option label="实习" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="招聘人数" prop="recruitmentCount">
              <el-input-number
                v-model="positionForm.recruitmentCount"
                :min="1"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="截止日期" prop="deadline">
              <el-date-picker
                v-model="positionForm.deadline"
                type="date"
                placeholder="请选择截止日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="岗位描述" prop="description">
              <el-input
                v-model="positionForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入岗位详细描述"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="任职要求" prop="requirements">
              <el-input
                v-model="positionForm.requirements"
                type="textarea"
                :rows="4"
                placeholder="请输入岗位任职要求"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="positionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitPositionForm"
            :loading="submitLoading"
          >
            {{ isEditing ? '更新' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useCompanyStore } from '../../store/company'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const companyStore = useCompanyStore()

const positions = ref([])
const loading = ref(false)
const positionDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitLoading = ref(false)
const isEditing = ref(false)
const positionFormRef = ref(null)
const selectedPosition = ref(null)

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 岗位表单数据
const positionForm = reactive({
  id: null,
  title: '',
  department: '',
  workLocation: '',
  salaryRange: '',
  workType: 3, // 默认为实习
  recruitmentCount: 1,
  deadline: '',
  description: '',
  requirements: ''
})

// 表单验证规则
const positionRules = {
  title: [{ required: true, message: '请输入岗位标题', trigger: 'blur' }],
  department: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
  workLocation: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  workType: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
  recruitmentCount: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }]
}

// 获取岗位列表
const fetchPositions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize
    }

    const response = await companyStore.fetchPositions(params)
    positions.value = response.content || response
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取岗位列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查看岗位详情
const viewPositionDetail = async (position) => {
  try {
    const detail = await companyStore.fetchPositionDetail(position.id)
    selectedPosition.value = detail
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取岗位详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取工作类型标签
const getWorkTypeLabel = (type) => {
  switch (type) {
    case 1: return '全职'
    case 2: return '兼职'
    case 3: return '实习'
    default: return '未知'
  }
}

// 获取岗位状态类型
const getPositionStatusType = (status) => {
  switch (status) {
    case 0: return 'info'   // 未上线
    case 1: return 'success' // 已上线
    case 2: return 'danger'  // 已下线
    default: return ''
  }
}

// 获取岗位状态标签
const getPositionStatusLabel = (status) => {
  switch (status) {
    case 0: return '未上线'
    case 1: return '已上线'
    case 2: return '已下线'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 显示创建对话框
const showCreateDialog = () => {
  isEditing.value = false
  resetPositionForm()
  positionDialogVisible.value = true
}

// 重置岗位表单
const resetPositionForm = () => {
  Object.assign(positionForm, {
    id: null,
    title: '',
    department: '',
    workLocation: '',
    salaryRange: '',
    workType: 3,
    recruitmentCount: 1,
    deadline: '',
    description: '',
    requirements: ''
  })

  // 清除验证状态
  if (positionFormRef.value) {
    positionFormRef.value.resetFields()
  }
}

// 编辑岗位
const editPosition = (position) => {
  isEditing.value = true
  Object.assign(positionForm, position)
  positionDialogVisible.value = true
}

// 提交岗位表单
const submitPositionForm = async () => {
  if (!positionFormRef.value) return

  await positionFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEditing.value) {
          const result = await companyStore.updatePosition(positionForm.id, positionForm)
          ElMessage.success('岗位更新成功')
        } else {
          const result = await companyStore.createPosition(positionForm)
          ElMessage.success('岗位发布成功')
        }

        positionDialogVisible.value = false
        fetchPositions()
      } catch (error) {
        ElMessage.error((isEditing.value ? '更新' : '发布') + '失败: ' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 处理岗位操作
const handlePositionAction = ({ action, position }) => {
  switch (action) {
    case 'toggle':
      togglePositionStatus(position)
      break
    case 'delete':
      deletePosition(position)
      break
  }
}

// 切换岗位状态（上线/下线）
const togglePositionStatus = async (position) => {
  try {
    await companyStore.togglePositionStatus(position.id)
    ElMessage.success(`${position.status === 0 ? '上线' : '下线'}成功`)
    fetchPositions()
  } catch (error) {
    ElMessage.error(`${position.status === 0 ? '上线' : '下线'}失败: ` + (error.response?.data?.message || error.message))
  }
}

// 删除岗位
const deletePosition = (position) => {
  ElMessageBox.confirm(`确定要删除岗位"${position.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await companyStore.deletePosition(position.id)
      ElMessage.success('删除成功')
      fetchPositions()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchPositions()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchPositions()
}

onMounted(() => {
  fetchPositions()
})
</script>

<style scoped>
.position-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.description-content,
.requirements-content {
  white-space: pre-wrap;
  line-height: 1.5;
}
</style>
